
#include "ADC.h"
#include "stm32f10x.h"
#include "stdio.h"


static void System_Config(void);

void ADC1_Init(void)
{

    NVIC_InitTypeDef NVIC_InitStructure;
    GPIO_InitTypeDef GPIOInitStruct;
    ADC_InitTypeDef InitStruct;

    System_Config();

    NVIC_InitStructure.NVIC_IRQChannel = ADC1_2_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);

    GPIOInitStruct.GPIO_Mode = GPIO_Mode_AIN;
    GPIOInitStruct.GPIO_Pin = GPIO_Pin_3;
    GPIOInitStruct.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIOInitStruct);


    ADC_DeInit(ADC1);
    InitStruct.ADC_NbrOfChannel = 1;
    InitStruct.ADC_ContinuousConvMode = ENABLE;
    InitStruct.ADC_DataAlign = ADC_DataAlign_Right;
    InitStruct.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
    InitStruct.ADC_ScanConvMode = ENABLE;
    InitStruct.ADC_Mode = ADC_Mode_Independent;
    ADC_Init(ADC1, &InitStruct);

    ADC_RegularChannelConfig(ADC1, ADC_Channel_3, 1, ADC_SampleTime_55Cycles5);

    ADC_ITConfig(ADC1, ADC_IT_EOC, ENABLE);

    ADC_Cmd(ADC1, ENABLE);

    ADC_SoftwareStartConvCmd(ADC1, ENABLE);
}



static void System_Config(void)
{

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA |
                           RCC_APB2Periph_ADC1 |
                           RCC_APB2Periph_ADC3, ENABLE);

}



void ADC1_2_IRQHandler(void)
{

    static uint32_t adcVal = 0;

    if(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == SET)
    {

        adcVal = ADC_GetConversionValue(ADC1);
        adcVal = adcVal * 3300;
        adcVal = adcVal / 4096;

        printf("\r\n----->val: %d\r\n", adcVal);

    }

}


void ADC1_Test(void)
{

    while(1)
    {

        uint32_t adcVal = 0;

        if(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == SET)
        {

            adcVal = ADC_GetConversionValue(ADC1);
            adcVal = adcVal * 3300;
            adcVal = adcVal / 4096;

            printf("\r\n----->val: %d\r\n", adcVal);

        }

    }


}

